/**
 * 添加项目
 */
import query from '../../untils/mysql';
import * as uuid from 'uuid';
import { Tip } from '../../untils/untils';
import { check, validationResult } from 'express-validator';

const validator = [
    check('projectID').notEmpty().withMessage("项目Id不能为空！"),
    check('phone').notEmpty().withMessage("手机号不能为空！"),
]
const POST = async (req: any, res: any, next: any) => {
    try {
        const { projectID, phone } = req.body;
        var errors = validationResult(req);
        if (!errors.isEmpty()) {
            return Tip.tipError(res, errors.array()[0].msg);
        }

        const popleData = await query(`select * from user where phone = '${phone}'`);
        if (popleData.length === 0) {
            return Tip.tipError(res, "该账号未注册");
        }
        let popleID = popleData[0].id;

        const projectData = await query(`select * from project_pople where pople_id = '${popleID}' and project_id = '${projectID}'`);
        if (projectData.length > 0) {
            return Tip.tipError(res, "当前账号已添加到当前项目");
        }

        await query(`insert into project_pople (id,project_id,pople_id) values ('${uuid.v1()}','${projectID}','${popleID}')`);
        return Tip.tipSuccess(res, '新增成功')
    } catch (error: any) {
        Tip.tipError500(res, error)
    }
}

export {
    POST,
    validator
}